library(tidyverse)
library(rstatix)
library(magrittr)
library(scales)
library(patchwork)

theme_set(theme_bw()+
            theme(panel.grid.minor = element_blank(),
                  panel.grid.major = element_blank()))


exp1_treat_labs <- c("1" = "control (C)",
                     "2" = "C +\nUN\nmediation\noffer",
                     "3" = "C +\nU.S.\nrescinds\nsupport",
                     "4" = "C +\npeaceful\nidentity\nrhetoric",
                     "5" = "C +\neconomic\ndevelopment\nrhetoric",
                     "6" =  "C +\neconomic\nsanction",
                     "7" = "C +\nno\nthreat"
)

exp2_treat_labs <- c("1" = "control (C)",
               "2" = "C +\nUN\nmediation\noffer",
               "3" = "C +\nU.S.\ndeterrent\nthreat",
               "4" = "C +\npeaceful\nidentity\nrhetoric",
               "5" = "C +\neconomic\ndevelopment\nrhetoric",
               "6" =  "C +\neconomic\nsanction",
               "7" = "C +\nno\nthreat"
)



x_names <- c("1" = "Control",
             "2" = "UN med",
             "3" = "US threat",
             "4" = "Peace id",
             "5" = "Econ dev",
             "6" =  "Sanction",
             "7" = "No threat"
)


df1 <- read_csv("exp1.csv") %>% 
  mutate(
    experiment = "E1 Japan Threat",
    fig_lab = "E1: Japanese Leader",
    pat_name = exp1_treat_labs[pat]
  )

df2 <- read_csv("exp2.csv") %>% 
  mutate(
    experiment = "E2 China Threat",
    fig_lab = "E2: Chinese Leader",
    pat_name = exp2_treat_labs[pat]
  )


df <- rbind(df1, df2) %>%
  mutate(
    waiver = s00,
    yob = s01,
    sex = s02,
    
    age = 2020 - yob,
    
    dom_rep = q05,
    intl_rep = q06,
    
  ) %>% filter(
    # Waiver
    waiver == 1,
    # Age (Japanese adult age = 20)
    age >= 20
  )

### Construct 7-point DV
df$approval <- NA
df$approval <- ifelse(df$q01 == 1, 
                      ifelse(!is.na(df$q02a), df$q02a + 6, NA),
                      df$approval)
df$approval <- ifelse(df$q01 == 0, 
                      ifelse(!is.na(df$q02b), 2 - df$q02b , NA),
                      df$approval)
df$approval <- ifelse(df$q01 == 9, 
                      ifelse(!is.na(df$q02c), df$q02c + 3, NA),
                      df$approval)

### Approval (binary)
df$approval_prop <- as.numeric(df$approval > 4)

####################
#### STATISTICS ####
####################

## Experiment 1: Japan threatens

t_test(detailed = T, approval ~ pat, data = df %>% 
         filter(experiment == "E1 Japan Threat"), 
       p.adj = "none", ref.group = 1) %>% 
  dplyr::select(!c(p.adj, p.adj.signif)) %>%
  add_significance("p") %>% print

t_test(detailed = T, dom_rep ~ pat, data = df %>% 
         filter(experiment == "E1 Japan Threat"), 
       p.adj = "none", ref.group = 1) %>% 
  dplyr::select(!c(p.adj, p.adj.signif)) %>%
  add_significance("p") %>% print

t_test(detailed = T, intl_rep ~ pat, data = df %>% 
         filter(experiment == "E1 Japan Threat"), 
       p.adj = "none", ref.group = 1) %>% 
  dplyr::select(!c(p.adj, p.adj.signif)) %>%
  add_significance("p") %>% print

## Experiment 2: China threatens

t_test(detailed = T, approval ~ pat, data = df %>% 
         filter(experiment == "E2 China Threat"), 
       p.adj = "none", ref.group = 1) %>% 
  dplyr::select(!c(p.adj, p.adj.signif)) %>%
  add_significance("p") %>% print

t_test(detailed = T, dom_rep ~ pat, data = df %>% 
         filter(experiment == "E2 China Threat"), 
       p.adj = "none", ref.group = 1) %>% 
  dplyr::select(!c(p.adj, p.adj.signif)) %>%
  add_significance("p") %>% print

t_test(detailed = T, intl_rep ~ pat, data = df %>% 
         filter(experiment == "E2 China Threat"), 
       p.adj = "none", ref.group = 1) %>% 
  dplyr::select(!c(p.adj, p.adj.signif)) %>%
  add_significance("p") %>% print

#####################
##### FIGURE 1 ######
#####################

summary_table_prop1 <- df %>% filter(experiment == "E1 Japan Threat") %>%
  group_by(pat) %>% 
  get_summary_stats(approval_prop)

summary_table_prop2 <- df %>% filter(experiment == "E2 China Threat") %>%
  group_by(pat) %>% 
  get_summary_stats(approval_prop)

panA <- ggplot(summary_table_prop1, aes(x = factor(pat), y = mean, ymin = mean - ci, ymax = mean + ci)) +
  scale_x_discrete(labels = exp1_treat_labs) +
  scale_y_continuous(labels = percent_format(suffix = "")) +
  geom_bar(stat = "identity", fill = c("grey40", rep('grey80', 6)), 
           color = 'black', width = 0.5) + 
  geom_errorbar(width = 0.2) + 
  labs(
    y = "Percentage approval (%)"
  ) +
  theme_bw() + 
  theme(
    axis.title.x = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
  )


panB <- ggplot(summary_table_prop2, aes(x = factor(pat), y = mean, ymin = mean - ci, ymax = mean + ci)) +
  scale_x_discrete(labels = exp2_treat_labs) + 
  scale_y_continuous(labels = percent_format(suffix = "")) +
  geom_bar(stat = "identity", fill = c("grey40", rep('grey80', 6)), 
           color = 'black', width = 0.5) + 
  geom_errorbar(width = 0.2) + 
  labs(
    y = "Percentage approval (%)"
  ) +
  theme_bw() + 
  theme(
    axis.title.x = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
  )

panA + panB + 
  theme(axis.title.y = element_blank(), 
        axis.text.y = element_blank(), 
        axis.ticks.y = element_blank()) + 
  plot_annotation(tag_levels = 'A')

ggsave("fig1.png", height = 6, width = 11)


#####################
##### FIGURE 2 ######
#####################

dom1 <- df %>% filter(experiment == "E1 Japan Threat") %>% group_by(fig_lab, experiment) %>%
  t_test(detailed = T, dom_rep ~ pat, p.adj = "none") %>% 
  filter(group1 == 1) %>% mutate(group1 = exp1_treat_labs[group1], group2 = exp1_treat_labs[group2]) %>%
  dplyr::select(!c(p.adj, p.adj.signif)) %>%
  add_significance("p") %>% 
  mutate(signif = p.signif != "ns")

dom2 <- df %>% filter(experiment == "E2 China Threat") %>% group_by(fig_lab, experiment) %>%
  t_test(detailed = T, dom_rep ~ pat, p.adj = "none") %>% 
  filter(group1 == 1) %>% mutate(group1 = exp2_treat_labs[group1], group2 = exp2_treat_labs[group2]) %>%
  dplyr::select(!c(p.adj, p.adj.signif)) %>%
  add_significance("p") %>% 
  mutate(signif = p.signif != "ns")

int1 <- df %>% filter(experiment == "E1 Japan Threat") %>% group_by(fig_lab, experiment) %>%
  t_test(detailed = T, intl_rep ~ pat, p.adj = "none") %>% 
  filter(group1 == 1) %>% mutate(group1 = exp1_treat_labs[group1], group2 = exp1_treat_labs[group2]) %>%
  dplyr::select(!c(p.adj, p.adj.signif)) %>%
  add_significance("p") %>% 
  mutate(signif = p.signif != "ns")

int2 <- df %>% filter(experiment == "E2 China Threat") %>% group_by(fig_lab, experiment) %>%
  t_test(detailed = T, intl_rep ~ pat, p.adj = "none") %>% 
  filter(group1 == 1) %>% mutate(group1 = exp2_treat_labs[group1], group2 = exp2_treat_labs[group2]) %>%
  dplyr::select(!c(p.adj, p.adj.signif)) %>%
  add_significance("p") %>% 
  mutate(signif = p.signif != "ns")

sum_tab <- rbind(dom1, dom2, int1, int2) 


sum_tab %<>% mutate(
  variable = case_when(
    `.y.` == "dom_rep" ~ "Domestic Reputation",
    `.y.` == "intl_rep" ~ "International Reputation"
  ),
  group2 = group2 %>% factor(
    levels = group2[c(1:2,8,3:6)] %>% as.vector
  )
)

p <- ggplot(data = sum_tab, aes(group2, -estimate, ymin =  -conf.high, ymax = -conf.low, color = factor(signif))) +
  geom_point() +
  geom_errorbar(width = 0.2) +
  geom_hline(yintercept = 0) +
  scale_color_manual(values = c('grey80', 'black')) +
  scale_y_continuous(labels = function(x) paste0(symnum(x, c(-Inf, 0, Inf), c("", "+")), x)) +
  labs(
    x = "Treatment Groups",
    y = "Difference from control",
  ) +
  facet_grid(variable ~ fig_lab, drop = T, scale = "free_x") +
  theme(legend.position = "none") 


## Modified from Package 'Egg' by Baptiste Auguie (GPL-3) to retain facet strip labels
##   see https://cran.r-project.org/web/packages/egg/index.html
tag_facet <- function(p, open = "(", close = ")", tag_pool = letters, x = -Inf, y = Inf, 
                      hjust = -0.5, vjust = 1.5, fontface = 2, family = "", ...) {
  gb <- ggplot_build(p)
  lay <- gb$layout$layout
  tags <- cbind(lay, label = paste0(open, tag_pool[lay$PANEL], close), x = x, y = y)
  p + geom_text(data = tags, aes_string(x = "x", y = "y", label = "label"), ..., hjust = hjust, 
                vjust = vjust, fontface = fontface, family = family, inherit.aes = FALSE) 
}

tag_facet(p, open = "", close = "",
          tag_pool = c("A","C","B",'D'))

ggsave("fig2.png", width = 9, height = 6)